<template>
  <div class="box">
    <div id="bing_tu" @click="clickChart"></div>

    <span class="unit">单位: {{ unit }}</span>
  </div>
</template>

<script setup>
  import * as echarts from "echarts"
  import { ref, reactive, watch, onMounted } from 'vue'

  const props = defineProps(['value'])

  const emit = defineEmits(['emitChartParams'])

  const unit = ref('')
  const options = reactive({
    tooltip: {
      trigger: "item",
      show: false,
    },
    // 提示
    tooltip: {
      trigger: "item",
      show: true,
    },
    legend: {
      top: "5%",
      left: "center",
      selectedMode: false,
      textStyle: {
        color: '#fff'
      },
      show: false
    },
    series: [
      {
        type: "pie",
        color:[
          'rgb(106, 240, 177)',
          'rgb(9, 117, 240)',
          'rgb(227, 233, 240)',
          'rgb(247, 183, 56)',
          'rgb(137, 240, 106)',
          'rgb(245, 138, 221)',
          'rgb(224, 85, 85)',
        ],
        radius: "50%",
        label: {
          color: '#fff',
          fontSize: 16,
          formatter: function(params) {
            return params.name + `{span|${params.value}}`
          },
          rich: {
            span: {
              color: '#fff',
              fontSize: '16px',
              fontWeight: '500',
              fontFamily: '',
            }
          }
        },
        data: [],
        itemStyle: {
          borderRadius: 1,
          borderColor: 'rgb(0, 0, 0, 0)',
          borderWidth: 6,
        },
      },
    ]
  })

  watch(() => props.value, 
    (newVal, oldVal) => {
      unit.value = newVal.unit
      let data = newVal.data
      options.series[0].data = data
      if (data) {
        initChart()
      }
    },
    {
      deep: true,
      // immediate: true
    }
  )

  onMounted(() => {
    initChart()
  })

  function initChart() {
    let chart = echarts.init(document.getElementById("bing_tu"));

    chart.on('click', params => {
      clickChart(params)
    })

    chart.setOption(options)
  }

  function clickChart(params) {
    emit('emitChartParams', params.data)
  }
</script>

<style scoped>
  .box {
    width: 100%;
    height: 100%;
    position: relative;
  }

  #bing_tu {
    width: 100%;
    height: 100%;
  }

  .unit { position: absolute; left: 10px; bottom: 0px; color: #fff; font-size: 10px; }
</style>
